<?php

namespace Biz\model\advertisement;


/**
 * @property mixed|null $id
 * @property null $type
 * @property null $bottom_background_image
 * @property null $photo
 * @property null $module_icon
 * @property null $main_title
 * @property null $sub_title
 * @property null $link_params
 * @property null $link_type
 * @property null $convert
 * @property null $linked_id
 */
class MCustomCard extends MBaseDbModel
{
    const _CONFIG_FILE_ = 'db_position';

    const _CONFIG_SELECT_ = 'db_position';

    const _DATABASE_ = 'hhz_position';

    const _TABLE_NAME = 'custom_card';


    const STATUS_NORMAL = 1;
    // 状态为删除
    const STATUS_DELETE = 9;

    const CUSTOM_CARD_TOPIC = 1;
    const CUSTOM_CARD_SIMILAR = 2;


    public static function getInfos($linked_ids): array
    {
        $list = self::select('*', ['linked_id' => $linked_ids, 'status' => self::STATUS_NORMAL]);
        if (empty($list)) return [];
        $list = array_map(function ($v) {return new self($v);}, $list);
        return array_column($list, null, 'linked_id');
    }

    public static function getInfo($linked_id): MCustomCard
    {
        return new self((array)self::get('*', ['linked_id' => $linked_id, 'status' => self::STATUS_NORMAL]));
    }

    public static function saved(MCustomCard $entity)
    {
        $linked_id = $entity->linked_id ?? 0;
        $data = [
            'type' => $entity->type ?? self::CUSTOM_CARD_TOPIC, //1主题卡片 2类原生卡片
            'photo' => $entity->photo ?? '', //背景图/封面图
            'module_icon' => $entity->module_icon ?? '', //模块图标
            'main_title' => $entity->main_title ?? '', //主标题
            'sub_title' => $entity->sub_title ?? '', //副标题
            'bottom_background_image' => $entity->bottom_background_image ?? '', //文字区背景图
            'convert' => $entity->convert ?? '', //发布者uid
            'link_type' => $entity->link_type ?? '', //链接类型
            'link_params' => json_encode($entity->link_params ?? [], JSON_UNESCAPED_UNICODE), //链接参数
            'linked_id' => $linked_id, //关联id
        ];

        if (self::exists($linked_id)) {
            self::update($data, ['linked_id' => $linked_id, 'status' => self::STATUS_NORMAL]);
        } else {
            self::insert($data);
            $id = self::id();
        }
    }

    public static function exists($linked_id)
    {
        return self::count(['linked_id' => $linked_id, 'status' => self::STATUS_NORMAL]);
    }
}

